//
//  WorkingTotalListController.swift
//  mggz
//
//  Created by ShareAnimation on 2017/8/25.
//  Copyright © 2017年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import MJRefresh

class WorkingTotalListController: BaseViewController {
    
    fileprivate var _tableView: UITableView!
    fileprivate var tableView: UITableView {
        get {
            if _tableView != nil {
                return _tableView
            }
            _tableView = UITableView()
            _tableView.delegate = self
            _tableView.dataSource = self
            _tableView.tableFooterView = UIView()
//            _tableView.separatorStyle = .none
            _tableView.showsVerticalScrollIndicator = false
//            _tableView.isScrollEnabled = false
            _tableView.backgroundColor = UIColor.mg_backgroundGray
            
            regClass(_tableView, cell: UITableViewCell.self)
            regClass(_tableView, cell: AccountBalanceCell.self)
            regClass(_tableView, cell: ProjectCell.self)
            regClass(_tableView, cell: SalaryApplyCell.self)
            
            return _tableView
        }
    }

    /***传入变量***/
    //当前项目模型
    var currentProjectModel: ProjectModel? {
        willSet {
            if newValue != nil {
                self.currentProjectModel = newValue //注意：willSet是在属性赋值前调用的，那么如果在这里设置这条语句，那么此时调用getDate()，currentProjectModel还是Nil的
                self.getDate()
            }
            else{
               // self.showErrorView(state: "没有数据！")
            }
            
        }
    }
    
    /***本地变量***/
    //总出工模型
    var workingTotalModel: StatisticsWorkingModel? {
        willSet {//将模型分解成数组，显示到tableView
            self.workingTotals = [String]()
            
            if newValue != nil {
                self.workingTotals!.append(newValue!.workingDays + "天")
                
                if self.currentProjectModel?.workDayType == 2{
                    self.workingTotals!.append(newValue!.workingHours + "小时")
                }else{
                    self.workingTotals!.append(newValue!.workingHours + "工")
                }
                
                self.workingTotals!.append(newValue!.workingDaysNotPayed + "天")
                self.workingTotals!.append(newValue!.workingHoursNotPayed + "工")
                self.workingTotals!.append(newValue!.payedSalaryAmount + "元")
            }
            else {
                self.workingTotals!.append("0" + "天")
                self.workingTotals!.append("0" + "小时")
                self.workingTotals!.append("0" + "天")
                self.workingTotals!.append("0" + "工")
                self.workingTotals!.append("0" + "元")
            }
        }
    }
    
    //工资请款模型
    var salaryApplyModel: [SalaryApplyModel]?
    
    var workingTotals: [String]?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.mg_backgroundGray
        
        self.view.addSubview(self.tableView)
        self.tableView.snp.makeConstraints { (make) in
            make.edges.equalTo(self.view)
        }
        
        let tableHeader = MJRefreshNormalHeader { [unowned self] in
            self.getDate()
        }
        tableHeader?.stateLabel.isHidden = true
        self.tableView.mj_header = tableHeader
        
//        self.showLoadingView()
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        WWProgressHUD.dismiss()
    }
    
    func getDate() {
        
        if let model = self.currentProjectModel, let demandBaseMigrantWorkerID = model.demandBaseMigrantWorkerID  {
            
           
            let dispatchGroup = DispatchGroup()
            
            dispatchGroup.enter()
            StatisticsWorkingModel.getStatisticsWorkingTotal(demandBaseMigrantWorkerID: demandBaseMigrantWorkerID) { (response) in
                if response.success {
                    self.workingTotalModel = response.value
                    
                }
                else {
                    
                    self.workingTotalModel = nil
                }
                self.tableView.reloadData()
                dispatchGroup.leave()
//                self.hideLoadingView()
            }
            
            dispatchGroup.enter()
            SalaryApplyModel.getApplyModelRecord(demandBaseMigrantWorkerID: demandBaseMigrantWorkerID){(response) in
                if response.success {
                    self.salaryApplyModel = response.value
                }
                else {
                   
                    self.salaryApplyModel = nil
                }
                
                self.tableView.reloadData()
                dispatchGroup.leave()
            }
//            self.hideLoadingView()
            
            dispatchGroup.notify(queue: DispatchQueue.main, execute: {
                if self.tableView.mj_header != nil {
                    self.tableView.mj_header.endRefreshing()
                }
            })
        }
        else {
           
            self.tableView.mj_header.endRefreshing()
        }
        

    }
}

extension WorkingTotalListController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 1 {
            if self.salaryApplyModel != nil {
                return self.salaryApplyModel!.count
            }
            else {
                return 0
            }
        }
        return 5
    }
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 1 {
            return 185
        }
        return 50
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//        let cell = getCell(tableView, cell: UITableViewCell.self, indexPath: indexPath)
        if indexPath.section == 0 {
            let cell = UITableViewCell.init(style: .value1, reuseIdentifier: "\(UITableViewCell.self)")
            
            if self.currentProjectModel?.workDayType == 2{
                cell.textLabel?.text = ["项目总出工天数", "总工时","未结算天数", "未结算工时数",  "已结算工资"][indexPath.row]
                
            }else{
               cell.textLabel?.text = ["项目总出工天数", "总工数","未结算天数", "未结算工数",  "已结算工资"][indexPath.row]
            }
            cell.textLabel?.font = wwFont_Medium(16)
            cell.detailTextLabel?.font = wwFont_Regular(16)
            
            if indexPath.row == 2 || indexPath.row == 3 {
                cell.textLabel?.textColor = UIColor.red
                cell.detailTextLabel?.textColor = UIColor.red
            }
            else {
                cell.textLabel?.textColor = UIColor.mg_lightGray
                cell.detailTextLabel?.textColor = UIColor.black
            }
            
            if self.workingTotals != nil {
                cell.detailTextLabel?.text = self.workingTotals![indexPath.row]
            }else{
                
                cell.detailTextLabel?.text = ["0天","0时","0天","0时","0元"][indexPath.row]
            }
            
            return cell
        }
        if indexPath.section == 1 {
            let cell = getCell(tableView, cell: SalaryApplyCell.self, indexPath: indexPath)
            guard self.salaryApplyModel != nil else {
                return cell
            }
            guard let model = self.salaryApplyModel?[indexPath.row] else {
                return cell
            }
            
            if model.salaryDate != nil {
                let dateString = dateToString(date: model.salaryDate!)
                cell.titleWithDateLabel.text = "第\(indexPath.row + 1)次工资" + dateString
            }
            
            cell.bind(model, workType: self.currentProjectModel?.workDayType ?? 0)
            return cell
        }
        return UITableViewCell()
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 1 {
            return 10
        }
        return 0.1
    }
}
